package com.lianboke.link.ad.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.lianboke.link.ad.R;
import com.lianboke.link.ad.Views.MyListView;
import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.ad.YOUMiADUitil;
import com.lianboke.link.ad.adapter.AdapterShipin;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.beans.LoginModel;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.location.LocationBean;
import com.lianboke.link.ad.locationservices.LocationService;
import com.lianboke.link.ad.services.LocationSvc;
import com.lianboke.link.ad.utils.ACache;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.MediaUtils;
import com.lianboke.link.ad.utils.MobclickAgentUtils;
import com.lianboke.link.ad.utils.SharedPreferencesUtil;
import com.lianboke.link.ad.utils.SystemExternalFileUtils;
import com.lianboke.link.ad.utils.SystemFileUtils;
import com.lianboke.link.ad.utils.ToastUtil;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.waps.AppConnect;

import static com.lianboke.link.ad.utils.ACache.TIME_DAY;

/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity{

//    private int GPS_REQUEST_CODE = 100;

    @BindView(R.id.et_username)
    public EditText et_username;
    @BindView(R.id.et_password)
    public EditText et_password;
    @BindView(R.id.btn_login_submit)
    public Button btn_login_submit;
    @BindView(R.id.login_progress)
    public ProgressBar login_progress;
    @BindView(R.id.btn_login_register)
    public Button btn_login_register;
    @BindView(R.id.checkBoxLogin)
    public CheckBox checkBoxLogin;

    @BindView(R.id.tv_shipin)
    public TextView tv_shipin;

    private ACache mACache;//缓存对此那个

    private String strUserName =null;//用户名
    private String strUserPwd = null;//密码
    private int iSaveUserValidity =7;//缓存天数


    //======================下载==================
    private AdapterShipin mAdapterShipin;
    @BindView(R.id.lv_shipin)
    public MyListView mShipinListView;
    private List<String> videoNetworkUrls = new ArrayList<String>();
    private int downLoadFileSize= 0;//需要下载的文件数量

    //==================百度地图==============
    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    private LocationService locationService;


    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
//        myLoginHandler  =new MyLoginHandler(this);
        setTitleBackShow(false);
        setTitleContent("登录");
        btn_login_submit.setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        //手动登录
                        checkLoginValue();
                    }
                }
        );
        btn_login_register.setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        gotoRegisterActiviy();
                    }

                });

        //初始化
        File pageFileDirs = SystemFileUtils.getAppDirectory(actContext);
        if(pageFileDirs!=null && pageFileDirs.exists()){
            File accountFile = new File(pageFileDirs, "ACache");
            if(accountFile!=null){
                mACache = ACache.get(accountFile);
            }
        }
        if(mACache==null){
            mACache = ACache.get(actContext);
        }
        //有米服务器托管
        YOUMiADUitil.setYOUMIUserInfo(actContext,DeviceUtils.getImei(actContext));
        //获取用户信息
        getUserCacheInfo();
        //初始化视频列表
        initShiPinAdapter();
        //获取视频信息
        getVidesUrlParmas();
        //获取权限
        getPersimmions();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopBaiDuLocation();
    }

    /**
     * 获取用户信息
     */
    public void getUserCacheInfo(){
        if(mACache!=null){
            strUserName=  mACache.getAsString("user_name");
            strUserPwd = mACache.getAsString("user_pwd");
        }else{
            strUserName =null;
            strUserPwd = null;
        }
    }



    /**
     * 获取值
     * @param editText
     * @return
     */
    public String getValueById(EditText editText){
        return editText.getText().toString().trim();
    }

    /**
     * 检测数据
     * @param value
     * @param content
     */
    public void checkViewValue(String value,String content){
        if(TextUtils.isEmpty(value)){
            hideLoginProgress();
            ToastUtil.showShort(actContext,content);
            return;
        }
    }
    public void showLoginProgress(){
        if(login_progress!=null && login_progress.getVisibility()!=View.VISIBLE){
            login_progress.setVisibility(View.VISIBLE);
        }
    }
    public void hideLoginProgress(){
        if(login_progress!=null && login_progress.getVisibility()!=View.GONE){
            login_progress.setVisibility(View.GONE);
        }
    }

    /**
     * 检查登录信息
     */
    public void checkLoginValue(){
        showLoginProgress();
        strUserName = getValueById(et_username);
        checkViewValue(strUserName,"请输入用户名");
        strUserPwd = getValueById(et_password);
        checkViewValue(strUserPwd,"请输入用户名");

        HashMap<String,String> params = new HashMap<String,String>();
        params.put("username",strUserName);
        params.put("password",strUserPwd);
        params.put("deviceid", DeviceUtils.getImei(actContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city",MyApplication.strCity);
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_LOGIN, params, new HttpCallBack<LoginModel>() {
            @Override
            public void onSuccess(LoginModel loginModel) {
                hideLoginProgress();
                if(loginModel.getStatus()==2) {
                    //保存用户数据
                    if(checkBoxLogin.isChecked()){
                        iSaveUserValidity = loginModel.getDays();
                        saveUserInfo();
                        saveUserVpnParams(loginModel.getVpnname(),loginModel.getVpnpass());
                    }else{
                        mACache.clear();
                    }
                    //跳转到主页面
                    gotomMainNewActiviy();
                }else {
                    String strMsg = loginModel.getTip();
                    if(TextUtils.isEmpty(strMsg)){
                        strMsg = "登录失败";
                    }
                    MobclickAgentUtils.UmengLoginEvent(appContext,params,21);
                    showAlerDialog(strMsg);
                }
            }

            @Override
            public void onFail(String msg) {
                hideLoginProgress();
                if(TextUtils.isEmpty(msg)){
                    msg = "登录失败!";
                }
                MobclickAgentUtils.UmengLoginEvent(appContext,params,22);
               showAlerDialog(msg);
            }
        });
    }
    /**
     * 保存用户信息
     */
    public void saveUserInfo(){
        if(mACache!=null){
            mACache.put("user_name",strUserName,TIME_DAY*iSaveUserValidity);
            mACache.put("user_pwd",strUserPwd,TIME_DAY*iSaveUserValidity);
        }
    }
    /**
     * 保存用户的vpn
     */
    public void saveUserVpnParams(String vpnName,String vpnPwd){
        MyApplication.strVpnName = vpnName;
        MyApplication.strVpnPwd = vpnPwd;
        SharedPreferencesUtil.saveData(appContext,"user_vpn_name",vpnName);
        SharedPreferencesUtil.saveData(appContext,"user_vpn_pwd",vpnPwd);
    }




    /**
     * 注册页面
     */
    public void gotoRegisterActiviy(){
        Intent mIntent = new Intent();
        mIntent.setClass(LoginActivity.this,RegisterActivity.class);
        startActivity(mIntent);
        finish();
    }
    /**
     * 跳转任务主页面
     */
    public void gotomMainNewActiviy(){
        Intent mIntent = new Intent();
        mIntent.setClass(LoginActivity.this,MainNewActivity.class);
        startActivity(mIntent);
        finish();
    }
    //================================百度定位=========================================
    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
			/*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }else{
            //初始化百度地图定位
            initBaiDuLocation();
            startBaiDuLocation();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SDK_PERMISSION_REQUEST) {
            if (!verifyPermissions(grantResults)) {
                //有部分权限未授予
                ToastUtil.showShort(actContext,"部分权限未被授予，将影响软件使用");
            }
            initBaiDuLocation();
            startBaiDuLocation();
        }
    }
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 开始百度定位
     */
    private void initBaiDuLocation(){
        locationService = ((MyApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mBaiDuLocationListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
    }
    private void startBaiDuLocation(){
        initCustomerLoadingDialog("定位中...");
        if(locationService!=null){
            locationService.start();
        }
    }

    /**
     * 停止定位服务
     */
    private void stopBaiDuLocation(){
        try {
            if(locationService.isStart()){
                locationService.unregisterListener(mBaiDuLocationListener); //注销掉监听
                locationService.stop(); //停止定位服务
            }
        }catch (Exception e){

        }
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mBaiDuLocationListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                //定位成功
                closedCustomerLoadingDialog();
                MyApplication.strCity = location.getCity();
                stopBaiDuLocation();
                KLog.e("city_log","---------------------city----------------"+location.getCity());
                //开始登录操作
                if (!TextUtils.isEmpty(strUserName) && !TextUtils.isEmpty(strUserPwd)) {
                    //执行自动登录
                    et_username.setText(strUserName);
                    et_password.setText(strUserPwd);
                    checkLoginValue();
                }
            }
        }

    };
//    //============================定位============================
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode==GPS_REQUEST_CODE){
//            checkLocationGRPPermission();
//        }
//    }
//
//    @Override
//    public void grantedPermission() {
//        //权限全部赋予，开始检测gps
//        checkLocationGRPPermission();
//    }
//
//    /**
//     * 检测定位中GPS 是否开启
//     */
//    public void checkLocationGRPPermission(){
//        if(DeviceUtils.isOpenGPS(actContext)){
//            //开启，开始获取定位数据
//            startLocationServer();
//        }else{
//            //非开启状态
//            new AlertDialog.Builder(this)
//                    .setTitle(R.string.notifyTitle)
//                    .setMessage(R.string.gpsNotifyMsg)
//                    // 拒绝, 退出应用
//                    .setNegativeButton(R.string.cancel,
//                            new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    finish();
//                                }
//                            })
//                    .setPositiveButton(R.string.setting,
//                            new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    //跳转GPS设置界面
//                                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                                    startActivityForResult(intent, GPS_REQUEST_CODE);
//                                }
//                            })
//                    .setCancelable(false)
//                    .show();
//        }
//    }
//
//    /**
//     * 开启定位服务信息
//     */
//    private void startLocationServer(){
//        initCustomerLoadingDialog("定位中...");
//        // 注册广播
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(LocationBean.LOCATION_ACTION);
//        this.registerReceiver(new LocationBroadcastReceiver(), filter);
//
//        // 启动服务
//        Intent intent = new Intent();
//        intent.setClass(this, LocationSvc.class);
//        startService(intent);
//    }
//
//    /**
//     * 定位信息接收器
//     */
//    public class LocationBroadcastReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            KLog.e("test_1","---------3333333333333333333---------:"+intent.getAction());
//            if (!intent.getAction().equals(LocationBean.LOCATION_ACTION)) {
//                return;
//            }
//            KLog.e("test_1","---------3333333333333333333---------");
//            //关闭对话框
//            closedCustomerLoadingDialog();
//            String locationInfo = intent.getStringExtra(LocationBean.LOCATION);
//            if(!TextUtils.isEmpty(locationInfo)) {
//                double latitude = Double.parseDouble(locationInfo.substring(17, 26));
//                double longitude = Double.parseDouble(locationInfo.substring(27, 37));
//                //获取地址
//                MyApplication.strCity = getaddress(latitude, longitude);
//            }else{
//                MyApplication.strCity = "山东聊城";
//            }
//            unregisterReceiver(this);
//            //开始登录操作
//            if (!TextUtils.isEmpty(strUserName) && !TextUtils.isEmpty(strUserPwd)) {
//                //执行自动登录
//                et_username.setText(strUserName);
//                et_password.setText(strUserPwd);
//                checkLoginValue();
//            }
//        }
//
//        /**
//         * 根据经纬度获取城市地址
//         * @param latitude
//         * @param longitude
//         * @return
//         */
//        public String getaddress(double latitude, double longitude) {
//            String cityName = "";
//            List<Address> addList = null;
//            Geocoder ge = new Geocoder(actContext);
//            try {
//                addList = ge.getFromLocation(latitude, longitude, 1);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if (addList != null && addList.size() > 0) {
//                for (int i = 0; i < addList.size(); i++) {
//                    Address ad = addList.get(i);
//                    cityName += ad.getCountryName() + ";" + ad.getLocality();
//                }
//            }
//            KLog.e("-----------the city ----------------:"+cityName);
//            return cityName;
//        }
//    }

    //=========================视频信息==========================

        /**
     * 初始化
     */
    public void initShiPinAdapter(){
        if(mAdapterShipin==null){
            mAdapterShipin = new AdapterShipin(actContext);
        }
        mShipinListView.setAdapter(mAdapterShipin);
        mShipinListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String strUrl = videoNetworkUrls.get(position);
                if(!TextUtils.isEmpty(strUrl) && strUrl.startsWith("http")){
                    MediaUtils.playerNetUrl(actContext,strUrl.trim());
                }else if(!TextUtils.isEmpty(strUrl) && !strUrl.startsWith("http")){
                    MediaUtils.playeVideoLocalUrl(actContext,"file://"+strUrl.trim(),"video/*");
                }else{
                    ToastUtil.show(actContext,"视频地址错误", Toast.LENGTH_LONG);
                }
            }
        });
    }

        /**
     * 检查教程视频信息
     */
    public void checkShouZhuanVideos(){
        //核对并创建文件夹
       String strDirs =  SystemExternalFileUtils.createDirByExternal("",CommonParams.DownLoadFileParams.FILE_DOWNLOAD_DIRS);
        List<String > filesPath = null;//文件夹下所有文件
        if(!TextUtils.isEmpty(strDirs)){
            //文件夹不为空
            filesPath = SystemExternalFileUtils.getParentFiles(strDirs);
        }
        if(downLoadFileSize>0 && filesPath.size()!=downLoadFileSize){
            //需要下载视频教程
            mAdapterShipin.setDatas(videoNetworkUrls);
            mShipinListView.setVisibility(View.VISIBLE);
            tv_shipin.setVisibility(View.VISIBLE);
        }else if(filesPath.size()>0){
            //展示视频地址列表
            videoNetworkUrls.clear();
            videoNetworkUrls.addAll(filesPath);
            mAdapterShipin.setDatas(videoNetworkUrls);
            mShipinListView.setVisibility(View.VISIBLE);
            tv_shipin.setVisibility(View.VISIBLE);
        }else{
            mShipinListView.setVisibility(View.GONE);
            tv_shipin.setVisibility(View.GONE);
        }
    }

    /**
     * 获视频数据
     */
    public void getVidesUrlParmas(){
        if(videoNetworkUrls!=null){
            videoNetworkUrls.clear();
        }
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("param","shipin");
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_SHIPIN, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String datas) {
                if(!TextUtils.isEmpty(datas)){
                    Log.e("file_log","-------getVidesUrlParmas-------onSuccess---:"+datas);
                    datas = datas.replaceAll("\"","");
                    String[] strUrls = datas.split("\\,");
                    if(strUrls!=null && strUrls.length>0){
                        downLoadFileSize = strUrls.length;
                        for (String msg:strUrls ) {
                            videoNetworkUrls.add(msg);
                        }
                    }
                    //检查信息
                    checkShouZhuanVideos();
                }
            }

            @Override
            public void onFail(String msg) {
                Log.e("file_log","-------getVidesUrlParmas------onFail----:"+msg);
                downLoadFileSize =0;
                if(videoNetworkUrls!=null){
                    videoNetworkUrls.clear();
                }
                checkShouZhuanVideos();
            }
        });
    }
}
